package cn.accjiyun.controller.website;

import cn.accjiyun.core.controller.BaseController;
import cn.accjiyun.core.entity.PageModel;
import cn.accjiyun.core.utils.WebUtils;
import cn.accjiyun.model.article.QueryArticle;
import cn.accjiyun.model.website.WebsiteBanner;
import cn.accjiyun.service.WebsiteBannerService;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by jiyun on 2017/2/11.
 */
@Controller
@RequestMapping("/admin/websiteBanner")
public class AdminBannerController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(AdminBannerController.class);

    private static String bannerListPage = getViewPath("/admin/website/banner-list");
    private static String addBannerPage = getViewPath("/admin/website/banner-add");

    @Autowired
    private WebsiteBannerService bannerService;
    @InitBinder({"banner"})
    public void initBinderSysUser(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("banner.");
    }

    @RequestMapping("/createBanner")
    @ResponseBody
    public String createBanner(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String sortString = request.getParameter("sort");
            //数据验证
            if (!WebUtils.isValidateRealString(sortString)
                    || !WebUtils.isNumeric(sortString)){
                resultJson.addProperty("status", 400);
                resultJson.addProperty("msg", "数据输入不合法！");
                return gson.toJson(resultJson);
            }
            WebsiteBanner banner = new WebsiteBanner();
            banner.setTitle(request.getParameter("title"));
            banner.setArticleUrl(request.getParameter("articleUrl"));
            banner.setImageUrl(request.getParameter("imageUrl"));
            banner.setSort(Integer.valueOf(sortString));
            bannerService.create(banner);
            //返回json数据
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "添加成功");
            resultJson.addProperty("url", "/admin/websiteBanner/initBannerList");
        } catch (Exception e) {
            logger.error("AdminBannerController.createBanner()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "添加失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String[] bannerIds = request.getParameter("bannerId").split(",");
            if (bannerIds != null && bannerIds.length > 0) {
                bannerService.deleteWebsiteBannerByIds(bannerIds);
            }
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "删除成功");
            resultJson.addProperty("url", "reload");
        } catch (Exception e) {
            logger.error("AdminBannerController.delete()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "删除失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }


    /**
     * 分页查询Banner列表
     */
    @RequestMapping("/getList")
    @ResponseBody
    public String getList(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            QueryArticle queryArticle = new QueryArticle();
            String pageNoString = request.getParameter("pageNo");
            if (!WebUtils.isValidateRealString(pageNoString) || !WebUtils.isNumeric(pageNoString)) {
                resultJson.addProperty("status", 400);
                resultJson.addProperty("msg", "数据输入不合法！");
                return gson.toJson(resultJson);
            }
            queryArticle.setQueryKey(request.getParameter("keyword"));
            queryArticle.setBeginCreateTime(WebUtils.stringToData(request.getParameter("start_date")));
            queryArticle.setEndCreateTime(WebUtils.stringToData(request.getParameter("end_date")));
            PageModel<WebsiteBanner> page = new PageModel<>();
            page.setPageSize(10);
            page.setPageNo(Integer.valueOf(pageNoString));
            List<WebsiteBanner> bannerList = bannerService.queryBannnerPage(queryArticle, page);
            JsonArray array = new JsonArray();
            for (WebsiteBanner banner : bannerList) {
                JsonObject list = new JsonObject();
                list.addProperty("bannerId", banner.getBannerId());
                list.addProperty("imageUrl", banner.getImageUrl());
                list.addProperty("sort", banner.getSort());
                list.addProperty("articleUrl", banner.getArticleUrl());
                list.addProperty("title", banner.getTitle());
                array.add(list);
            }
            JsonObject list = new JsonObject();
            list.add("list", array);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("pages", page.getTotalPageSize());
            resultJson.add("data", list);
        } catch (Exception e) {
            logger.error("AdminBannerController.getList()--error", e);
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    /**
     * 修改Banner
     */
    @RequestMapping("/update")
    @ResponseBody
    public String update(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String bannerIdString = request.getParameter("bannerId");
            String sortString = request.getParameter("sort");
            //数据验证
            if (!WebUtils.isValidateRealString(sortString, bannerIdString)
                    || !WebUtils.isNumeric(sortString, bannerIdString)){
                resultJson.addProperty("status", 400);
                resultJson.addProperty("msg", "数据输入不合法！");
                return gson.toJson(resultJson);
            }
            WebsiteBanner banner = bannerService.queryWebsiteBannerById(Integer.valueOf(bannerIdString));
            banner.setTitle(request.getParameter("title"));
            banner.setArticleUrl(request.getParameter("articleUrl"));
            banner.setImageUrl(request.getParameter("imageUrl"));
            banner.setSort(Integer.valueOf(sortString));

            bannerService.updateWebsiteBanner(banner);
            // 修改成功返回原列表页面
            resultJson.addProperty("status", 200);
            resultJson.addProperty("url", "reload");
            resultJson.addProperty("msg", "更新成功");
        } catch (Exception e) {
            logger.error("AdminBannerController.update()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "更新失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/initAddBanner")
    public ModelAndView initAddBanner() {
        ModelAndView model = new ModelAndView();
        model.setViewName(addBannerPage);
        return model;
    }

    @RequestMapping("/initBannerList")
    public ModelAndView initBannerList() {
        ModelAndView model = new ModelAndView();
        model.setViewName(bannerListPage);
        return model;
    }

}
